package com.davidmartos96.sqflite_sqlcipher;

import android.util.Log;

import net.sqlcipher.database.SQLiteDatabase;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class SqfliteSqlCipherTool {

    public static boolean hasKey(String path) {
        File file = new File(path);
        boolean result = false;
        if (file.exists()) {
            String header = getFileHeader(path);
            result = !header.startsWith("SQLite format 3");
        }
        return result;
    }

    public static boolean encryptDatabase(String path, String password) {
        return changeEncryptedDatabase(path,"", password);
    }

    public static boolean unencryptDatabase(String path, String password) {
        return changeEncryptedDatabase(path,password, "");
    }

    public static boolean changeEncryptedDatabase(String path, String oldPassword, String newPassword) {
        File file = new File(path);
        boolean result = false;
        if (!file.exists()) {
            return false;
        }
        String tempPath = String.format("%s.temp1.db", path);
        File tempFile = new File(tempPath);
        SQLiteDatabase db = null;
        try {
            boolean res = tempFile.createNewFile();
            db = SQLiteDatabase.openDatabase(path, (oldPassword == null ? "" : oldPassword), null, SQLiteDatabase.OPEN_READWRITE);
            db.rawExecSQL(String.format("ATTACH DATABASE '%s' AS encrypted Key '%s'", tempFile.getAbsolutePath(), newPassword));
            db.rawExecSQL("begin exclusive transaction");
            db.rawExecSQL("SELECT sqlcipher_export('encrypted');");
            db.rawExecSQL("commit transaction");
            db.rawExecSQL("DETACH DATABASE encrypted;");
            result = true;
        } catch (Exception e) {
            Log.e("TAG", "changeEncryptedDatabase: " + e.getMessage());
        } finally {
            if (result) {
                String tempPath2 = String.format("%s.temp.db", path);
                File tempFile2 = new File(tempPath2);
                boolean res = file.renameTo(tempFile2);
                res = tempFile.renameTo(file);
                if (!res) {
                    tempFile2.renameTo(file);
                }
                tempFile2.delete();
                tempFile.delete();
            }
            if (db != null) {
                db.close();
            }
        }
        return result;
    }

    // 获取数据库文件的首字符串
    public static String getFileHeader(String filePath) {
        FileInputStream is = null;
        String value = null;
        try {
            is = new FileInputStream(filePath);
            byte[] b = new byte[16];
            is.read(b, 0, b.length);
            value = new String(b);
        } catch (Exception e) {
            Log.e("TAG", "getFileHeader: " + e.getMessage());
        } finally {
            if(null != is) {
                try {
                    is.close();
                } catch (IOException e) {

                }
            }
        }
        return value;
    }
}
